using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace OA.UI
{
    public static class Utils
    {
        #region URL

        public static UrlHelper Url { get { return new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext); } }

        /// <summary>
        /// 获取资源当前的地址
        /// </summary>
        /// <param name="resourceCode">资源编号</param>
        /// <returns></returns>
        public static string GetCurrentPath(string resourceCode)
        {
            string currentPath = "";
            if (!string.IsNullOrEmpty(resourceCode))
            {
                var menu = new BLL.Menu().GetModel(Common.Keys.WebSiteCode, resourceCode);
                string websiteName = null;
                if (menu != null)
                {
                    websiteName = menu.WebSite.Name;
                    while (menu != null)
                    {
                        currentPath = menu.Name + " > " + currentPath;
                        menu = menu.Parent;
                    }
                    currentPath = websiteName + " > " + currentPath;
                }
            }
            return currentPath;
        }

        /// <summary>
        /// 获取资源的连接的绝对地址
        /// </summary>
        public static string GetMenuHrefUrl(Model.Menu value)
        {
            return GetMenuHrefUrl(value, null);
        }

        /// <summary>
        /// 获取资源的连接的绝对地址
        /// </summary>
        public static string GetMenuHrefUrl(Model.Menu value, string parmes, params string[] ps)
        {
            var url = value.Address;
            if (!string.IsNullOrEmpty(url) && url.StartsWith("/"))
            {
                url = value.WebSite.Address + url;
            }
            return GetUrlParames(url,parmes,ps);
        }

        /// <summary>
        /// 将url转换为html绝对地址
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="parmes">加到URL后的参数，以逗号分隔多个参数</param>
        /// <param name="ps">参数的值</param>
        /// <returns></returns>
        public static string GetUrlParames(string url, string parmes, params string[] ps)
        {
            string ret = url;
            if (!string.IsNullOrEmpty(parmes))
            {
                Dictionary<string, string> newps = new Dictionary<string, string>();
                var us= url.Split('?');
                ret = us[0];
                if (us.Length > 1 && !string.IsNullOrEmpty(us[1]))
                {
                    var oldparmes = us[1];
                    foreach (var oldparme in oldparmes.Split('&'))
                    {
                        if (!string.IsNullOrEmpty(oldparme))
                        {
                            var pp = oldparme.Split('=');
                            if (pp.Length > 1 && !string.IsNullOrEmpty(pp[0]))
                            {
                                newps[pp[0]] = pp[1];
                            }
                        }
                    }
                }
                var parmesArray = parmes.Split(',');
                for (var i = 0; i < parmesArray.Length; i++)
                {
                    newps[parmesArray[i]] = ps[i];
                }
                StringBuilder query = new StringBuilder();
                foreach (var p in newps)
                {
                    query.Append("&" + p.Key + "=" + System.Web.HttpUtility.UrlEncode(p.Value));
                }
                query.Remove(0, 1);
                ret += "?" + query.ToString();
            }
            return ret;
        }

        /// <summary>
        /// 连接到指定资源(以tab形式在主窗口中打开)
        /// </summary>
        /// <param name="resourceCode">资源编号</param>
        /// <param name="parmes">加到URL后的参数，以逗号分隔多个参数</param>
        /// <param name="ps">参数的值</param>
        /// <returns></returns>
        public static string LinkToMenu(string menuCode, string parmes, params string[] ps)
        {
            var bll = new BLL.Menu();
            var menu = bll.GetModel(Common.Keys.WebSiteCode, menuCode);
            var path = GetMenuHrefUrl(menu, parmes, ps);
            var ret = string.Format("mainAddTab('{0}','{1}',{2},'{3}')",
                menu.Name, path, true.ToString().ToLower(), menu.IconCls);
            return ret;
        }

        #endregion



        public static string FormateDate(DateTime? date)
        {
            return date == null ? null : date.Value.ToString(Common.Keys.DATEFORMAT).Replace('-', '/');
        }


        public static ActionResult ErrorDateNoExist()
        {

            return ErrorPage("错误", "要修改的数据不存在");
        }

        public static ActionResult ErrorPage(string title, string msg)
        {
            return new RedirectResult(GetUrlParames(Url.Action("Error", "Home"), "Title,Message", title, msg));
        }

        public static string ToJsonString(object obj)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
        }


        /// <summary>
        /// 获取分页url
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示数</param>
        /// <param name="count">数据总数</param>
        /// <param name="parmes">为分布url添加的额外参数名称，以逗号分隔多个参数</param>
        /// <param name="ps">额外的参数值</param>
        /// <returns></returns>
        public static string GetPageLink(int page, int rows, int count, string parmes, params object[] ps)
        {
            if (!string.IsNullOrEmpty(parmes))
            {
                var parmesArray = parmes.Split(',');
                parmes = "";
                for (int i = 0; i < parmesArray.Length; i++)
                {
                    parmes += "&" + parmesArray[i] + "=" + ps[i].ToString();
                }
            }

            StringBuilder sb = new StringBuilder();
            if (page > 1)
            {
                sb.Append(string.Format("<a href=\"?rows={0}&page=1{1}\">第一页</a>", rows, parmes));
                sb.Append(string.Format("<a href=\"?rows={0}&page={1}{2}\">上一页</a>", rows, page - 1, parmes));
            }
            else
            {
                sb.Append("<span>第一页</span>");
                sb.Append("<span>上一页</span>");
            }
            var allPages = count / rows + (count % rows > 0 ? 1 : 0);
            if (allPages == 0) allPages = 1;
            sb.Append(string.Format("<span class=\"pagecount\">{0}/{1}</span>", page, allPages));
            if (page < allPages)
            {
                sb.Append(string.Format("<a href=\"?rows={0}&page={1}{2}\">下一页</a>", rows, page + 1, parmes));
                sb.Append(string.Format("<a href=\"?rows={0}&page={1}{2}\">最后页</a>", rows, allPages, parmes));
            }
            else
            {
                sb.Append("<span>下一页</span>");
                sb.Append("<span>最后页</span>");
            }
            return sb.ToString();
        }
    }
}
